package bd

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import oa.lla.cca.R
import oa.lla.cca.databinding.FragmentImageSourceBinding
import com.clean.scanlibrary.dialog.LoadingDialog
import com.clean.scanlibrary.img.adapter.PicSelectAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.ArrayList
import java.util.concurrent.CountDownLatch

class FD : FH() {
    private var databind: FragmentImageSourceBinding? = null
    private var adapter: PicSelectAdapter? = null
    private val imgLists: ArrayList<FB> = ArrayList()
    private var selectAllList : ArrayList<FB>? = null
    private var countDownLatch:CountDownLatch? = null
    private var loadingDialog: LoadingDialog? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        databind = FragmentImageSourceBinding.inflate(inflater)
        return databind!!.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView(){
        loadingDialog =
            LoadingDialog(requireActivity(), R.style.dialog)
        loadingDialog?.show()


        val viewMode = ViewModelProvider(requireActivity()).get(FI::class.java)
        databind?.apply {
            imgLists.clear()
            imageSourceList.layoutManager = GridLayoutManager(requireActivity(),3)
            adapter = PicSelectAdapter(imgLists,requireActivity())
            imageSourceList.adapter = adapter
            viewMode.imageSourceLiveData.observe(requireActivity()
            ) { t ->

                loadingDialog?.dismiss()
                if (t.isNotEmpty()) {
                    imgLists.addAll(t!!)
                    if(imgLists.size>0){
                        emptyLayout.visibility =View.GONE
                        adapter?.notifyDataSetChanged()
                    }else{
//                        emptyLayout.text = "暂无搜索到相关文件"
                        emptyLayout.visibility =View.VISIBLE
                    }
                    selectNum.text = "(0/${imgLists.size})"

                }
            }
            //选中操作
            adapter?.setOnItemSelectClickListener(object :
                PicSelectAdapter.OnItemSelectClickListener{
                override fun selectIndex(bean: ArrayList<FB>) {
                    selectAllList = bean
                    if (selectAllList!=null){
                        selectNum.text = "(${selectAllList!!.size}/${imgLists.size})"
                    }
                }
            })


            //删除文件
            sourceDeleteBt.setOnClickListener {
                if (selectAllList!=null && selectAllList!!.size>0){
                    showAd(true,"image_del")
                }else{
                    Toast.makeText(requireActivity(),"请至少选中一个文件",Toast.LENGTH_SHORT).show()
                }
            }
            //恢复文件
            sourceRecoverBt.setOnClickListener {
                if (selectAllList!=null && selectAllList!!.size>0){
                    showAd(false,"image_recover")
                }else{
                    Toast.makeText(requireActivity(),"请至少选中一个文件",Toast.LENGTH_SHORT).show()
                }
            }

            //全选操作
            selectAll.setOnClickListener {
                initSelect(true)
            }

            //全选操作
            selectCancel.setOnClickListener {
                initSelect( false)
            }
        }
    }


    private fun initSelect(isSelect:Boolean){
        if (imgLists.size<=0){
            return
        }
        for (item in imgLists){
            item.isSelect = isSelect
        }
        adapter?.notifyDataSetChanged()
    }


    private fun saveLocation(str:String){
        //通过Glide 生成Bitmap
        Glide.with(this).asBitmap().load(str).into(object : SimpleTarget<Bitmap>(){
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                val saveBitmap2Gallery = FE.saveBitmapGallery(requireActivity(), resource)
                countDownLatch!!.countDown()
            }
            override fun onLoadFailed(errorDrawable: Drawable?) {
                super.onLoadFailed(errorDrawable)
                countDownLatch!!.countDown()
            }
        })
    }

    private fun recoverFile(){
        countDownLatch = CountDownLatch(selectAllList!!.size)
        lifecycleScope.launch (Dispatchers.Main){
            withContext(Dispatchers.IO){
                countDownLatch?.await()
            }
            Toast.makeText(requireActivity(),"保存成功", Toast.LENGTH_SHORT).show()
        }
        for (item in selectAllList!!) {
            saveLocation(item.path)
        }
    }



    private fun showAd(isDelete:Boolean,adKey:String){
        if (isDelete){
            deleteFiles()
        }else{
            recoverFile()
        }
    }

    private fun deleteFiles(){
        lifecycleScope.launch(Dispatchers.Main){
            withContext(Dispatchers.IO){
                for (item in selectAllList!!) {
                    File(item.path).delete()
                    imgLists.remove(item)
                }
            }
            selectAllList?.clear()
            Toast.makeText(requireActivity(),"删除成功", Toast.LENGTH_SHORT).show()
            adapter?.notifyDataSetChanged()
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && data!=null){
            val intExtra = data.getIntExtra(CH.POSITION, 0)
            imgLists.removeAt(intExtra)
            adapter?.notifyDataSetChanged()
        }
    }



    companion object {
        private var instance: FD? = null
        @JvmStatic
        fun newInstance(): FD {
            if (instance ==null){
                instance = FD()
            }
            return instance!!
        }
    }
}